package com.suitsoft.ut.commons;

import java.util.Date;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;


import com.suitsoft.ut.entity.account.Authority;
import com.suitsoft.ut.entity.account.Role;
import com.suitsoft.ut.entity.system.TimeAuthority;
import com.suitsoft.ut.util.DateUtils;


/**
 * 时间控制 权限
 * <pre>根据权限的时间段，来控制标签内的内容</pre>
 *@author Suineg
 */
public class TimeControlerTag extends TagSupport{
	/**
	 * 
	 */
	private static final long serialVersionUID = 8200873139915304677L;
	
	/** 权限名 */
	private String authName;
	
	@Override
	public int doStartTag() throws JspException {
		try {
			Date now = new Date();
			boolean f = false;
			for(Role r : UserHolder.getLoginUser().getRoleList()){
				if(r.getAuthNames().indexOf(authName) != -1){
					Authority authority = getAuth(r,authName);
					//如果，此权限没开启 时间控制时,直接显示标签内容
					if(authority.getEffective() == Constants.TIME_CONTROL_NOT_EFFECTIVE){
						return EVAL_BODY_INCLUDE; 
					}
					for(TimeAuthority ta : authority.getTimeAuthority()){
						if(DateUtils.isContain(ta.getStartDate(), ta.getEndDate(), now)){
							return EVAL_BODY_INCLUDE;
						}
					}
					return SKIP_BODY;
				}
			}
			if(!f){
				return SKIP_BODY;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return SKIP_BODY;
		
	}
	
	private Authority getAuth(Role r,String authName){
		for(Authority a : r.getAuthorityList()){
			if(a.getName().equals(authName)){
				return a;
			}
		}
		return null;
	}

	public void setAuthName(String authName) {
		this.authName = authName;
	}
	
}

